from .view import Model, ModelView
from . import schema
from typing import List
from fastapi import APIRouter, Depends, Security
from package.connector.sql_db import db
from package.fastapi import permission


router_model = APIRouter(prefix='/model', tags=['数据模型'])
router_meta = {'module': '数据采集', 'sub_module': '数据模型'}


@router_model.get('/', response_model=schema.PageModels, openapi_extra=router_meta, name='model_list_get',
                 summary='数据模型列表')
def model_list_get(q: str = None,
             page: int = 1,
             page_size: int = 10,
             order_by: str = 'created_at desc',
             session=Depends(db.get_session),
             user=Security(permission.security, scopes=['model:read'])):
    return ModelView.get_page_items(session, q=q, page=page, page_size=page_size, order_by=order_by)


@router_model.post('/', response_model=schema.ModelOut, openapi_extra=router_meta, name='model_post', summary='数据模型创建')
def model_post(body: schema.CreateModel,
              session=Depends(db.get_session),
              user=Security(permission.security, scopes=['model:write'])):
    return ModelView.create_model(session, body=body.dict())


@router_model.get('/{id}', response_model=schema.ModelOut, openapi_extra=router_meta, name='model_get',
                 summary='数据模型详情')
def model_get(id: str,
             session=Depends(db.get_session),
             user=Security(permission.security, scopes=['model:read'])):
    return ModelView.get_item(session, filter_=[Model.id == id])


@router_model.patch('/{id}', response_model=schema.ModelOut, openapi_extra=router_meta, name='model_patch',
                   summary='数据模型修改')
def model_patch(id: str,
               body: schema.EditModel,
               session=Depends(db.get_session),
               user=Security(permission.security, scopes=['model:write'])):
    return ModelView.update_model(session, filter_=[Model.id == id], update=body.dict(exclude_unset=True))


@router_model.delete('/', openapi_extra=router_meta, name='model_delete', summary='数据模型删除')
def model_delete(body: schema.BatchId,
                session=Depends(db.get_session),
                user=Security(permission.security, scopes=['model:write'])):
    return {'count': ModelView.delete_models(session, filter_=[Model.id.in_(body.ids)])}


@router_model.post('/helper/index', openapi_extra=router_meta, name='helper_index', summary='索引搜索帮助')
def helper_index(body: dict,
    session=Depends(db.get_session),
              user=Security(permission.security, scopes=['model:write'])):
    return ModelView.helper_index(session, body=body.dict())
